/**
 * Global Vars
 * 
 * @param {type} url
 * @returns {@exp;$@call;trim}
 */
var isPageLoading = false;
var isFormSubmitting = false;

/**
 * Toast Message Config
 * 
 * @type type
 */
toastr.options = {
  "closeButton": false,
  "debug": false,
  "positionClass": "toast-bottom-full-width",
  "onclick": null,
  "showDuration": "500",
  "hideDuration": "500",
  "timeOut": "5000",
  "extendedTimeOut": "500",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
};

/**
 * Site url
 * 
 * @param {type} url
 * @returns {@exp;$@call;trim}
 */
function siteUrl(url) {
  url = (url === undefined || url === '') ? '' : url;
  return $.trim($('#site_url').val() + url);
}

/**
 * Set redirect to url
 * 
 * @param {type} href
 * @returns {undefined}
 */
function setRedirectUrl(href) {
  $("#redirect_url").val(href);
  $("#redirect_to").val(href); // For quick signin
}

/**
 * Get redirect to url
 * 
 * @returns {@exp;$@call;trim}
 */
function getRedirectUrl() {
  return $.trim($('#redirect_url').val());
}

/**
 * System routing
 * 
 */
function routeController() {
  var curUrl;
  $(document).ready(function() {
    $('body').on('click', '.route-controller', function(event) {
      event.preventDefault();
      curUrl = $(this).attr('href');
      setRedirectUrl(curUrl);
      if ($(this).hasClass('confirm-action')) {
        var href = $(this).attr('href');
        var confirm = $(this).attr('confirm');
        confirmAction(href, confirm);
      } else {
        loadPage(curUrl);
      }
    });
    $('body').on('click', '.route-controller-non', function(event) {
      event.preventDefault();
      if ($(this).hasClass('confirm-action')) {
        var href = $(this).attr('href');
        var confirm = $(this).attr('confirm');
        confirmAction(href, confirm);
      } else {
        loadPage($(this).attr('href'));
      }
    });
    $(window).on('popstate', function() {
      if (curUrl !== location.href) {
        loadPage(location.href);
      }
    });
  });
}

/**
 * Confirm Action
 * 
 * @param {type} href
 * @param {type} confirm
 * @returns {undefined}
 */
function confirmAction(href, confirm) {
  bootbox.confirm(confirm, function(result) {
    if (result) {
      loadPage(href);
    }
  });
}

/**
 * Load page content
 * 
 * @param {type} href
 * @returns {undefined}
 */
function loadPage(href) {
  if (isPageLoading) {
    return false;
  } else {
    isPageLoading = true;
  }
  NProgress.start();
  $.router.go(href);
  NProgress.set(0.4);
  $.ajax({
    url: href,
    type: 'GET',
    success: function(data) {
      isPageLoading = false;
      $("#content").html(data);
      $('html, body').animate({scrollTop: $('html').offset().top}, 1000);
      NProgress.done();
    },
    error: function() {
      location.reload();
    }
  });
}

/**
 * Submit Ajax Form
 * 
 * @param {type} form
 * @returns {undefined}
 */
function submitAjaxForm(form) {
  if (isFormSubmitting) {
    return false;
  } else {
    isFormSubmitting = true;
  }
  var formUrl = $(form).attr('url');
  if (formUrl) {
    $.router.go(formUrl);
  }
  NProgress.start();
  var formAction = $(form).attr('action');
  var formMethod = $(form).attr('method');
  var formData = $(form).serialize();
  $(form.find('input, select, button')).attr('disabled', 'true');
  NProgress.set(0.4);
  $.ajax({
    url: formAction,
    type: formMethod,
    data: formData,
    success: function(data) {
      isFormSubmitting = false;
      $("#content").html(data);
      $('html, body').animate({
        scrollTop: $('.container').offset().top
      }, 1000);
      $(form.find('input, select, button')).removeAttr('disabled');
      NProgress.done();
    },
    error: function() {
      location.reload();
    }
  });
}

/**
 * Set Location
 * 
 * @param {type} loc
 * @returns {undefined}
 */
function setLocation(loc) {
  var locKey = (loc.value !== undefined) ? loc.value : loc;
  $.ajax({
    url: siteUrl('location/set?id=' + locKey),
    type: 'POST',
    success: function() {
      loadPage(getRedirectUrl());
    }
  });
}

/**
 * Get Location List Dropdown
 * 
 * @returns {undefined}
 */
function getLocationDropdownList() {
  $(document).ready(function() {
    $('#location_name').typeahead({
      ajax: {
        url: siteUrl('location/dropdown'),
        triggerLength: 1,
        loadingClass: 'textbox_data_loading'
      },
      onSelect: setLocation
    });
  });
}

/**
 * Initilize the sidebar filter
 * 
 * @returns {undefined}
 */
function initFilter() {
  $(document).ready(function() {
    $('.sidebar-panel-body').collapse();
    $(".sidebar-panel-body").niceScroll();
    $('#filter_form').find("input[type='checkbox']").on('change', function() {
      submitAjaxForm($('#filter_form'));
    });
  });
}

/**
 * Select all checkbox in a particular filter box
 * 
 * @param {type} element
 * @param {type} checkall
 * @param {type} submitForm
 * @returns {undefined}
 */
function selectAllCheckbox(element, checkall, submitForm) {
  if (checkall) {
    $($('#' + element).find("input[type='checkbox']")).attr('checked', 'true');
  } else {
    $($('#' + element).find("input[type='checkbox']")).removeAttr('checked', 'true');
  }
  if (submitForm) {
    submitAjaxForm($('#filter_form'));
  }
}

/**
 * Search in Filter Box
 * 
 * @param {type} that
 * @param {type} element
 * @returns {undefined}
 */
function searchFilterBox(that, element) {
  var name = that.value.toLowerCase();
  $('#' + element).find('ul').each(function() {
    if ($(this).text().toLowerCase().search(name) > -1) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
}

/**
 * Reset sidebar filter form
 * 
 * @returns {undefined}
 */
function resetFilter() {
  resetForm($('#filter_form'));
  submitAjaxForm($('#filter_form'));
}

/**
 * Reset all inputs in a form
 * 
 * @param {type} $form
 * @returns {undefined}
 */
function resetForm($form) {
  $form.find('input:text, input:password, input:file, select, textarea').val('');
  $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}

/**
 * Search filter for Category Items & Brands
 * 
 * @param {type} that
 * @param {type} element
 * @returns {undefined}
 */
function searchCategory(that, element) {
  var name = that.value.toLowerCase();
  $('.cat-search-value').each(function() {
    if ($(this).text().toLowerCase().search(name) > -1) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
}

/**
 * Change type of password fields in a form
 * 
 * @param {type} that
 * @param {type} formId
 * @returns {undefined}
 */
function showHidePassword(that, formId) {
  if ($('#' + formId).find('input').attr('type') === 'password') {
    $('#' + formId).find('input').attr('type', 'text');
    $(that).find('i').removeClass('fa-eye');
    $(that).find('i').addClass('fa-eye-slash');
    $(that).attr('title', 'Make Passwords Hidden');
  } else {
    $('#' + formId).find('input').attr('type', 'password');
    $(that).find('i').removeClass('fa-eye-slash');
    $(that).find('i').addClass('fa-eye');
    $(that).attr('title', 'Make Passwords Visible');
  }
}

/**
 * Select Picker Plugin Element Intilization
 * 
 * @returns {undefined}
 */
function initSelectPicker() {
  $(document).ready(function() {
    $('#user_type').selectpicker();
    $('#advert_type').selectpicker();
    $('#advert_category').selectpicker();
    $('#advert_item').selectpicker();
    $('#advert_item_type').selectpicker();
    $('#advert_price_type').selectpicker();
    $('#advert_price_currency').selectpicker();
    $('#advert_brand').selectpicker();
    $('#advert_brand_model').selectpicker();
  });
}

/**
 * Get Url Parameter
 * 
 * @param {type} name
 * @returns {getUrlParam.match}
 */
function getUrlParam(name) {
  var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

/**
 * Change Advert Category
 * 
 * @param {type} that
 * @returns {Boolean}
 */
function advertChangeCategory(that) {
  var textInputed = false;
  var catUrl = siteUrl('advert/publish?category=' + that.value);
  $('#publish_advert').find('input').each(function() {
    if (this.value) {
      textInputed = true;
    }
  });
  if (textInputed) {
    var curCat = (getUrlParam('category')) ? getUrlParam('category') : 1;
    $('#advert_category').val(curCat);
    $('#advert_category').selectpicker('render');
    confirmAction(catUrl, 'Are you sure to discard this advert and change category ?');
  } else {
    loadPage(catUrl);
  }
  return false;
}

/**
 * Set Price Value
 * 
 * @returns {undefined}
 */
function setPriceValue() {
  var dealType = $('#advert_price_type').val();
  if (dealType === '1' || dealType === '2') {
    $('#advert_price_value').val('');
    $('#advert_price_section').fadeIn();
  } else {
    $('#advert_price_value').val('');
    $('#advert_price_section').fadeOut();
  }
}

/**
 * Ajax Image Upload
 * 
 * @param {type} count
 * @param {type} path
 * @param {type} elem_key
 * @returns {undefined}
 */
function initAjaxImageUpload(count, path, elem_key) {
  $(document).ready(function() {
    $('#' + elem_key + '_file').simpleAjaxUpload({
      fileAttrName: elem_key + '_file',
      maxFileUpload: count,
      uploadAddr: siteUrl(path),
      autoSubmit: true,
      inOneGo: false,
      callbackOnFileSelected: function() {
        $('#' + elem_key + '_uploaded').val('');
        $('#' + elem_key + '_message').html('0 files selected');
        $('#' + elem_key + '_progress').attr('style', 'width:' + 0 + '%');
      },
      callbackBeforeQueueStart: function(listQueue) {
        $('#' + elem_key + '_message').html(listQueue.length + ' files selected');
      },
      callbackEachNodeBeforeUpload: function(currentNodeNumber, totalQueue) {
        $('#' + elem_key + '_message').html('Uploading ' + (currentNodeNumber + 1) + ' of ' + totalQueue);
      },
      callbackUploadProgress: function(event) {
        var percentage = Math.round((event.loaded / event.total * 100));
        $('#' + elem_key + '_progress').attr('style', 'width:' + percentage + '%');
      },
      callbackEachNode: function(currentNodeNumber, totalQueue, data) {
        if (data.serverReturn.file !== undefined) {
          createImgIds(elem_key, data.serverReturn.file);
        } else {
          showImgErr(elem_key, data.serverReturn.error);
        }
        $('#' + elem_key + '_message').html('Uploaded ' + (currentNodeNumber + 1) + ' of ' + totalQueue);
      },
      callbackOnFinishedAll: function(data) {
        var files = [];
        if (data.length !== undefined && data.length > 0) {
          for (var i = 0; i < data.length; i++) {
            if (data[i].serverReturn.file !== undefined) {
              files.push(data[i].serverReturn.file);
            }
          }
        }
        if (files.length) {
          $('#' + elem_key + '_uploaded').val('yes');
        } else {
          $('#' + elem_key + '_uploaded').val('');
        }
        $('#' + elem_key + '_uploaded').keyup();
      }
    });
  });
}

/**
 * Create Image Hidden Fields
 * 
 * @param {type} elem_key
 * @param {type} value
 * @returns {undefined}
 */
function createImgIds(elem_key, value) {
  $('<input>').attr({
    type: 'hidden',
    name: elem_key + '_id[]',
    class: elem_key + '_id',
    value: value
  }).appendTo($('#' + elem_key + '_form_group'));
}

/**
 * Remove Image Hidden Field
 * 
 * @param {type} elem_key
 * @returns {undefined}
 */
function removeImgIds(elem_key) {
  $('.' + elem_key + '_id').remove();
  $('#' + elem_key + '_uploaded').val('');
  $('#' + elem_key + '_form_group').removeClass('has-error');
  $('#' + elem_key + '_form_group .help-block').hide().html('');
}

/**
 * Show Image Upload Error
 * 
 * @param {type} elem_key
 * @param {type} value
 * @returns {undefined}
 */
function showImgErr(elem_key, value) {
  value = (value !== undefined) ? value : 'Unknown error occured. Try again later !';
  $('#' + elem_key + '_form_group').addClass('has-error');
  $('#' + elem_key + '_form_group .help-block').show().html(value);
}